<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'device:fault:faultManagement:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <div class="fireVeIm">
      <div class="fireImg">
        <span>
          处理结果图片:
        </span>
        <Image v-if="imageSrc" :src="imageSrc" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" alt="">
      </div>
    </div>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Equipment_Failure_Process"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'device:fault:faultManagement:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsDeviceFaultFaultManagementForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { FaultManagement, faultManagementSave, faultManagementForm } from '/@/api/device.fault/faultManagement';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('device.fault.faultManagement');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<FaultManagement>({} as FaultManagement);
  const loadingRef = ref(false);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增设备故障信息') : t('编辑设备故障信息'),
  }));
  const imageSrc = ref('')
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('故障发生主体的ID'),
      field: 'subjectId',
      show: false,
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('故障发生主体的名称'),
      field: 'subjectName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('区域ID'),
      field: 'regionId',
      component: 'Input',
      show: false,
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
      componentProps: {
        disabled: true,
      }
    },
    {
      label: t('区域名称'),
      field: 'regionName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('建筑ID'),
      field: 'buildingId',
      component: 'Input',
      show:false,
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
      componentProps: {
        disabled: true,
      }
    },
    {
      label: t('建筑名称'),
      field: 'buildingName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('故障类型'),
      field: 'faultType',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('设备ID'),
      field: 'deviceId',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('设备名称'),
      field: 'deviceName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('所属主机ID'),
      field: 'hostId',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('所属主机名称'),
      field: 'hostName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('记录创建时间'),
      field: 'createTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        disabled: true
      },
    },
    {
      label: t('记录最后更新时间'),
      field: 'updateTime',
      component: 'DatePicker',
      show: false,
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        disabled: true
      },
    },
    {
      label: t('恢复正常图片的ID'),
      field: 'recoveryImageId',
      show: false,
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('恢复正常图片的URL'),
      field: 'recoveryImageUrl',
      show: false,
      component: 'Input',
    },
    {
      label: t('处理人ID'),
      field: 'handlerId',
      component: 'Input',
      show: false,
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('处理人姓名'),
      field: 'handlerName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('处理人联系方式'),
      field: 'handlerContact',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('处理方式'),
      field: 'handlingMethod',
      show:()=>{return record.value.bpm.activityId=='s68fd981fb'},
      component: 'Select',
      componentProps: {
        maxlength: 255,
        options:[
          {label:"与企业人员沟通",value:'1'},
          {label:"直接处理",value:'2'}
        ]
      },
    },
    {
      label: t('是否恢复'),
      field: 'isRecovered',
      component: 'Select',
      show:()=>{return record.value.bpm.activityId=='s860bd66eb'},
      componentProps: {
        options:[
          {label:"是",value:'1'},
          {label:"否",value:'2'}
        ]

      }
    },
    // {
    //   label: t('图片上传'),
    //   field: 'dataMap',
    //   component: 'Upload',
    //   componentProps: {
    //     loadTime: computed(() => record.value.__t),
    //     bizKey: computed(() => record.value.id),
    //     bizType: 'faultManagement_image',
    //     uploadType: 'image',
    //   },
    //   colProps: { md: 24, lg: 24 },
    // },
    {
      label: t('恢复正常证明'),
      field: 'dataMap',
      component: 'Upload',
      show:()=>{return record.value.handlingMethod=='2' || record.value.isRecovered=='1'},
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'faultManagement_file',
        fileUrl: computed(() => record.value.fileUrl),
        uploadType: 'image',
        maxNumber: 1,
      },
      colProps: { md: 24, lg: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await faultManagementForm(data);
    console.log('res', res);
    imageSrc.value = res.faultManagement.recoveryImageUrl
    record.value = (res.faultManagement || {}) as FaultManagement;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      let data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data = { ...data, 
        recoveryImageUrl:(data.dataMap.faultManagement_fileUrl != null) ? (data.dataMap.faultManagement_fileUrl.split('?')[0]) : record.value.recoveryImageUrl,
        recoveryImageId:(data.dataMap.faultManagement_file != null) ? data.dataMap.faultManagement_file : record.value.recoveryImageId
       };
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      // console.log('submit', params, data, record);
      const res = await faultManagementSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
<style scoped lang="less"> 
.fireVeIm{
  display: flex;
  justify-content: space-start;
  align-items: center;
  margin-bottom: 5%;
  margin-left: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
}
</style>